package com.shadow.controller;

import com.shadow.common.bo.R;
import com.shadow.common.bo.SysConstants;
import com.shadow.common.entity.QuartzJob;
import com.shadow.srvice.QuartzService;
import com.shadow.common.util.ApiResp;
import com.shadow.common.util.CronUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * Quartz Controller
 *
 */
@RestController
@RequestMapping("/quartz")
public class QuartzController {

    @Resource
    private QuartzService quartzService;

    /**
     * api 返回使用，状态
     */
    protected int success = 0;
    protected int error = 1;
    private static final String CRON_ERROR = "cron表达式不正确";

    /**
     * 获取定时任务列表
     */
    @GetMapping("/getList")
    public R getList() {
        return R.successForLayUi(quartzService.getList(), 10);
    }

    /**
     * 新增定时任务
     */
    @PostMapping("add")
    public R add(@RequestBody QuartzJob job) throws Exception {
        if (CronUtils.isValid(job.getCronExpression())) {
            quartzService.add(job);
            return R.success();
        }
        return R.fail(CRON_ERROR);
    }

    /**
     * 更新定时任务
     */
    @PostMapping("update")
    public ApiResp<QuartzJob> update(@RequestBody QuartzJob job) throws Exception {
        if (!CronUtils.isValid(job.getCronExpression())) {
            return ApiResp.<QuartzJob>builder().code(error).msg("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确").build();
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), SysConstants.LOOKUP_RMI)) {
            return ApiResp.<QuartzJob>builder().code(error).msg("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi://'调用").build();
        } else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), SysConstants.LOOKUP_LDAP)) {
            return ApiResp.<QuartzJob>builder().code(error).msg("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap://'调用").build();
        }
        quartzService.updateJob(job);
        return ApiResp.<QuartzJob>builder().code(success).build();
    }

    @PostMapping("changeStatus")
    public ApiResp<Object> changeStatus(Long jobId, String status) throws SchedulerException {
        quartzService.changeStatus(jobId, status);
        return ApiResp.builder().code(success).build();
    }

    /**
     * 执行一次
     */
    @PostMapping("run")
    public R runJob(@RequestBody QuartzJob quartzJob) throws SchedulerException {
        quartzService.runJob(quartzJob);
        return R.success();
    }

    /**
     * 删除
     */
    @PostMapping("del")
    public R del(@RequestBody QuartzJob quartzJob) throws SchedulerException {
        int i = quartzService.deleteJob(quartzJob);
        return i == 1 ? R.success() : R.fail();
    }

}
